﻿using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace UFrame
{
    /// <summary>
    /// 调试鼠标悬浮在那个UGUI上面
    /// </summary>
    public class UGUIOverGUI : MonoBehaviour
    {
        public GraphicRaycaster gr;
        public static GraphicRaycaster staticGR;
        public bool isDebug = false;
        public static bool isStaticDebug = false;
        public bool isOverDebug = false;

        void Start()
        {
            if (gr == null)
                gr = GetComponent<GraphicRaycaster>();
            if (gr == null)
                gr = FindObjectOfType<GraphicRaycaster>();

            staticGR = gr;
            isStaticDebug = isDebug;
        }

        void Update()
        {
            if (isOverDebug)
            {
                var go = GetOverUI(gr);
                if (go != null)
                    Debug.Log(go.name);
            }
        }

        public static GameObject GetOverUI(GraphicRaycaster gr = null)
        {
            if (gr == null)
                gr = staticGR;
            if (gr == null)
                return null;

            PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
            pointerEventData.position = Input.mousePosition;
            List<RaycastResult> results = new List<RaycastResult>();
            gr.Raycast(pointerEventData, results);

            if (isStaticDebug)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < results.Count; i++)
                {
                    sb.AppendLine(results[i].gameObject.name);
                }

                Debug.Log("鼠标点击的UGUI " + sb.ToString());
            }

            if (results.Count != 0)
            {
                return results[0].gameObject;
            }

            return null;
        }
    }
}